package com.cx.jsjmybatis.controller;

import com.cx.jsjmybatis.mapper.StudentMapper;
import com.cx.jsjmybatis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiang
 * @date 2025/10/15
 */
@RestController
@RequestMapping("/api/student")
public class IndexController {

    @Autowired
    private StudentMapper studentMapper;

    // 1. 新增学生
    @PostMapping("/add")
    public Map<String, Object> create(@RequestBody Student student) {
        int result = studentMapper.insert(student);
        Map<String, Object> response = new HashMap<>();
        if (result > 0) {
            response.put("success", true);
            response.put("message", "添加成功");
            response.put("data", student); // 包含生成的 id
        } else {
            response.put("success", false);
            response.put("message", "添加失败");
        }
        return response;
    }

    // 2. 删除学生（按 ID）
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Integer id) {
        int result = studentMapper.deleteById(id);
        Map<String, Object> response = new HashMap<>();
        if (result > 0) {
            response.put("success", true);
            response.put("message", "删除成功");
        } else {
            response.put("success", false);
            response.put("message", "删除失败，ID 不存在");
        }
        return response;
    }

    @PutMapping
    public Map<String, Object> update(@RequestBody Student student) {
        int result = studentMapper.update(student);
        Map<String, Object> response = new HashMap<>();
        if (result > 0) {
            response.put("success", true);
            response.put("message", "更新成功");
        } else {
            response.put("success", false);
            response.put("message", "更新失败，ID 不存在");
        }
        return response;
    }

    @GetMapping("/{id}")
    public Map<String, Object> findById(@PathVariable Integer id) {
        Student student = studentMapper.selectById(id);
        Map<String, Object> response = new HashMap<>();
        if (student != null) {
            response.put("success", true);
            response.put("data", student);
        } else {
            response.put("success", false);
            response.put("message", "未找到该学生");
        }
        return response;
    }

    @GetMapping
    public Map<String, Object> findAll() {
        List<Student> students = studentMapper.selectAll();
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", students);
        return response;
    }
}